<?php

class CpModule {

    public function setcardpos() {
        global $_FANWE;

        $id = intval($_POST['id']);
        if(!$id) exit;

        if(empty($_POST['lat']) || !is_numeric($_POST['lat']) || empty($_POST['lng']) || !is_numeric($_POST['lng'])) {
            exit(json_encode(array(
                'status' => 1,
                'msg' => '请先设置位置'
            )));
        }

        $data = array(
            'lat' => $_POST['lat'],
            'lng' => $_POST['lng'],
        );

        FDB::update('wogu_card', $data, array('id' => $id));
        exit(json_encode(array(
            'status' => 0,
            'id' => $id
        )));
    }

    public function delcard() {
        global $_FANWE;

        $id = intval($_GET['id']);
        $sql = 'SELECT * FROM '.FDB::table('wogu_card')." WHERE id='{$id}'";
        $card = FDB::fetchFirst($sql);
        if(!$card) {
            exit;
        }

        for($i = 1; $i <= 6; $i++) {
            $key = 'pic'.$i;
            if(!empty($card[$key])) {
                unlink('.'.$card[$key]);
            }
        }

        $sql = 'DELETE FROM '.FDB::table('wogu_card')." WHERE id={$id}";
        FDB::query($sql);
        exit(json_encode(array(
            'status' => 1
        )));
    }

    public function delcardimg() {
        global $_FANWE;

        $id = intval($_POST['id']);
        $img = htmlspecialchars($_POST['img']);
        if(!$id || empty($img)) {
            exit;
        }

        $img = str_replace($_FANWE['site_url'].'.', '', $img);
        $sql = 'SELECT * FROM '.FDB::table('wogu_card')." WHERE id='{$id}'";
        $card = FDB::fetchFirst($sql);
        if(!$card) {
            exit;
        }

        for($i = 1; $i <= 6; $i++) {
            $key = 'pic'.$i;
            if($card[$key] == $img) {
                $sql = 'UPDATE '.FDB::table('wogu_card')." SET {$key}='' WHERE id={$id}";
                FDB::query($sql);
            }
        }

        exit(json_encode(array(
            'status' => 0
        )));
    }

    protected function getpickey($card) {
        for($i = 1; $i <= 6; $i++) {
            if(empty($card['pic'.$i])) {
                return $i;
            }
        }

        return false;
    }

    public function sendcardimg() {
        global $_FANWE;

        $id = intval($_GET['id']);
        $sql = 'SELECT * FROM '.FDB::table('wogu_card')." WHERE id='{$id}'";
        $card = FDB::fetchFirst($sql);
        if(!$card) {
            exit(json_encode(array(
                'error' => '请柬不存在'
            )));
        }

        $pickey = self::getpickey($card);
        if(false === $pickey) {
            exit(json_encode(array(
                'error' => '最多上传6张图片'
            )));
        }

        $fkey = 'img';
        $whitelist = array('jpg', 'jpeg', 'png', 'gif');
        $name      = null;
        $error     = 'No file uploaded.';
        if (isset($_FILES)) {
            if (isset($_FILES[$fkey])) {
                $extension = pathinfo($_FILES[$fkey]['name'], PATHINFO_EXTENSION);
                $tmp_name = $_FILES[$fkey]['tmp_name'];
                $name     = './public/upload3/'.date('Y').'/'.date('md').'/'.md5(microtime(true).random('6')).'.'.$extension;
                $dir = dirname($name);
                if(!is_dir($dir)) mkdir($dir, 0777, true);
                $error = $_FILES[$fkey]['error'];
                if ($error === UPLOAD_ERR_OK) {
                    if (!in_array($extension, $whitelist)) {
                        $error = 'Invalid file type uploaded.';
                    } else {
                        if(move_uploaded_file($tmp_name, $name)) {
                            FDB::update('wogu_card', array('pic'.$pickey => substr($name, 1)), array('id' => $id));
                        }
                    }
                }
            }
        }

        echo json_encode(array(
            'name'  => $name,
            'error' => $error
        ));
        exit;
    }

    public function mycardview() {
        global $_FANWE;

        $data['user_type'] = $_FANWE['user']['user_type'];
        $id = intval($_GET['id']);
        if($id) {
            $sql = 'SELECT * FROM '.FDB::table('wogu_card')." WHERE id='{$id}'";
            $card = FDB::fetchFirst($sql);
            if($card) {
                $data['data']['id'] = $id;
                $data['data']['date'] = date('Y-m-d', $card['dateline']);
                $data['data']['time'] = date('H:i', $card['dateline']);
                $data['data']['bridegroom'] = $card['bridegroom'];
                $data['data']['bride'] = $card['bride'];
                $data['data']['content'] = $card['content'];
                $data['data']['address'] = $card['address'];
                $data['data']['lat'] = $card['lat'];
                $data['data']['lng'] = $card['lng'];
                $data['imgs'] = array();
                for($i = 1; $i <= 6; $i++) {
                    if(!empty($card['pic'.$i])) {
                        $data['imgs'][] = $card['pic'.$i];
                    }
                }
            }
        }

        exit(json_encode($data));
    }

    public function mycard() {
        global $_FANWE;

        $sql = 'SELECT * FROM '.FDB::table('wogu_card').' WHERE uid = '.$_FANWE['uid'] . ' ORDER BY id DESC';
        $data = FDB::fetchAll($sql);
        if(!empty($data)) {
            foreach ($data as &$v) {
                $v['dateline'] = date('Y-m-d', $v['dateline']);
                $v['share_title'] = empty($v['bride']) ? '敬请参加公司年会' : "敬请参加{$v['bride']},{$v['bridegroom']}的婚礼";
                $v['share_des'] = "时间:{$v['dateline']},地点:{$v['address']}";
            }
        }
        exit(json_encode(array(
            'list' => $data
        )));
    }

    public function sendcard() {
        global $_FANWE;

        $bridegroom = $bride = '';
        if($_FANWE['user']['user_type'] == 0) {
            $bridegroom = htmlspecialchars(trim($_POST['bridegroom']));
            $bride = htmlspecialchars(trim($_POST['bride']));
            if(empty($bridegroom)) {
                exit(json_encode(array(
                    'status' => 1,
                    'msg' => '新郎姓名不能为空'
                )));
            }
            if(empty($bride)) {
                exit(json_encode(array(
                    'status' => 1,
                    'msg' => '新娘姓名不能为空'
                )));
            }
        }

        $address = htmlspecialchars(trim($_POST['address']));
        if(empty($address)) {
            exit(json_encode(array(
                'status' => 1,
                'msg' => '地点不能为空'
            )));
        }

        $date = htmlspecialchars(trim($_POST['date']));
        $time = htmlspecialchars(trim($_POST['time']));
        if(empty($date) || empty($time)) {
            exit(json_encode(array(
                'status' => 1,
                'msg' => '日期时间不能为空'
            )));
        }

        $content = htmlspecialchars(trim($_POST['content']));
        if(empty($content)) {
            exit(json_encode(array(
                'status' => 1,
                'msg' => '请柬内容不能为空'
            )));
        }

        $dateline = strtotime($data.' '.$time);
        $data = array(
            'bridegroom' => $bridegroom,
            'bride' => $bride,
            'address' => $address,
            'dateline' => $dateline,
            'content' => $content,
        );

        $id = intval($_POST['id']);
        if($id) {
            FDB::update('wogu_card', $data, array('id' => $id));
        } else {
            $data['uid'] = $_FANWE['uid'];
            $id = FDB::insert('wogu_card', $data, true);
        }

        exit(json_encode(array(
            'status' => 0,
            'id' => $id
        )));
    }

    public function myredview() {
        global $_FANWE;

        $tips = array('恭喜发财，大吉大利', '财源广进', '一路顺丰', '生活美满');

        if(!is_numeric($_GET['code']) || strlen($_GET['code']) != 6) exit;
        $sql = 'SELECT * FROM '.FDB::table('wogu_red_my')." WHERE code='{$_GET['code']}'";
        $red = FDB::fetchFirst($sql);
        if(!$red) exit;

        $sql = 'SELECT * FROM '.FDB::table('wogu_red_log').' WHERE my_id='.$red['id'];
        $logs = FDB::fetchAll($sql);
        $curruser = array();
        if(!$red['flag']) {
            if(!empty($logs)) {
                $num = 0;
                $curr = 1;
                $money = $red['money'] * 100;
                foreach ($logs as $v) {
                    $num++;
                }

                foreach ($logs as &$v) {
                    if($curr == $num) {
                        $v['money'] = $money;
                    } else {
                        $randmoney = $money - ($num - $curr); // 至少保证每人能领一分钱
                        $v['money'] = rand(1, $randmoney);
                        $money -= $v['money'];
                    }

                    $v['dateline'] = date('Y-m-d');
                    $v['avatar'] = avatar($v['avatar'], 'b');
                    $tipkey = array_rand($tips);
                    $v['tip'] = $tip = $tips[$tipkey];
                    $sql = 'UPDATE '.FDB::table('wogu_red_log')." SET money={$v['money']},tip='{$tip}' WHERE id={$v['id']}";
                    FDB::query($sql);
                    $v['money'] = sprintf('%.2f', $v['money']/100);
                    $curr++;

                    if($v['uid'] == $_FANWE['uid']) $curruser = $v;
                    // 充值到余额
                    $sql = 'UPDATE '.FDB::table('user').' SET rmb_yu=rmb_yu+'.$v['money'].' WHERE uid='.$v['uid'];
                    FDB::query($sql);
                }

                $sql = 'UPDATE '.FDB::table('wogu_red_my')." SET flag=1 WHERE id={$red['id']}";
                FDB::query($sql);
            }
        } else {
            $num = 0;
            foreach ($logs as &$v) {
                $v['dateline'] = date('Y-m-d');
                $v['avatar'] = avatar($v['avatar'], 'b');
                $v['money'] = sprintf('%.2f', $v['money']/100);
                if($v['uid'] == $_FANWE['uid']) $curruser = $v;
                $num++;
            }
        }

        exit(json_encode(array(
            'logs' =>$logs,
            'red' => $red,
            'curruser' => $curruser,
            'num' => $num
        )));
    }

    public function myredlog() {
        global $_FANWE;

        $sql = 'SELECT * FROM '.FDB::table('wogu_red_log').' WHERE uid = '.$_FANWE['uid'].' AND dateline<'.(time()-45).' ORDER BY id DESC';
        $data = FDB::fetchAll($sql);
        if(!empty($data)) {
            foreach ($data as &$v) {
                $v['dateline'] = date('Y-m-d');
                $v['money'] = sprintf('%.2f', $v['money']/100);
            }
        }
        exit(json_encode(array(
            'list' => $data
        )));
    }

    public function qiangred() {
        global $_FANWE;
        if(!is_numeric($_GET['code']) || strlen($_GET['code']) != 6) {
            exit(json_encode(array(
                'status' => 1,
                'msg' => '红包口令错误'
            )));
        }

        $sql = 'SELECT * FROM '.FDB::table('wogu_red_my')." WHERE code='{$_GET['code']}'";
        $red = FDB::fetchFirst($sql);
        if(!$red) {
            exit(json_encode(array(
                'status' => 2,
                'msg' => '红包不存在'
            )));
        }

        $sql = 'SELECT * FROM '.FDB::table('wogu_red_log')." WHERE my_id='{$red['id']}' AND uid={$_FANWE['uid']}";
        $oldred = FDB::fetchFirst($sql);
        if($oldred) {
            exit(json_encode(array(
                'status' => 4,
                'msg' => '您已经抢过该红包'
            )));
        }

        $curr = time();
        $time = $curr - $red['dateline'];
        if($time < 30) {
            $data = array(
                'my_id' => $red['id'],
                'uid' => $_FANWE['uid'],
                'username' => $_FANWE['user_name'],
                'shopname' => $red['shopname'],
                'code' => $red['code'],
                'dateline' => $curr,
                'avatar' => $_FANWE['avatar']
            );
            FDB::insert('wogu_red_log', $data);
            exit(json_encode(array(
                'status' => 0,
                'time' => $time
            )));
        }

        exit(json_encode(array(
            'status' => 3,
            'time' => $time,
            'red' => $red,
            'dateline' => $curr,
            'msg' => '很遗憾，此红包已经失效!'
        )));
    }

    protected function _getcode() {
        global $_FANWE;

        while (true) {
            $code = rand(100000, 999999);
            $sql = 'SELECT * FROM '.FDB::table('wogu_red_my')." WHERE code='{$code}'";
            $red = FDB::fetchFirst($sql);
            if(!$red) {
                return $code;
            }
        }
    }

    public function sendred() {
        global $_FANWE;

        $where = 'uid='.$_FANWE['uid'].' AND flag=0';
        if(!empty($_GET['redid'])) {
            $redids = explode(',', $_GET['redid']);
            foreach ($redids as $k => $redid) {
                if(!is_numeric($redid)) unset($redids[$k]);
            }
            $where .= ' AND id IN('.implode(',', $redids).')';
        }

        $sql = 'SELECT * FROM '.FDB::table('wogu_red').' WHERE '.$where;
        $reds = FDB::fetchAll($sql);
        if(!empty($reds)) {
            $money = 0;
            $redids = $shopnames = array();
            foreach ($reds as $red) {
                $money += $red['money'];
                $redids[] = $red['id'];
                $shopnames[] = $red['shop_name'];
            }
            $code = self::_getcode();
            $dateline = time();
            $redids = implode(',', $redids);
            $data = array(
                'uid' => $_FANWE['uid'],
                'redids' => $redids,
                'shopname' => implode(',', $shopnames),
                'money' => $money,
                'dateline' => $dateline,
                'code' => $code
            );
            if(FDB::insert('wogu_red_my', $data)) {
                FDB::query("UPDATE ".FDB::table('wogu_red')." SET flag=1,dateline={$dateline},code='{$code}' WHERE id IN({$redids})");
                exit(json_encode(array(
                    'status' => 1,
                    'code' => $code
                )));
            }
        }

        exit(json_encode(array(
            'status' => 0
        )));
    }

    public function myred() {
        global $_FANWE;

        $sql = 'SELECT * FROM '.FDB::table('wogu_red').' WHERE uid = '.$_FANWE['uid'].' ORDER BY flag ASC,id DESC';
        $data = FDB::fetchAll($sql);
        if(!empty($data)) {
            foreach ($data as &$v) {
                $v['dateline'] = date('Y-m-d');
            }
        }
        exit(json_encode(array(
            'list' => $data
        )));
    }

    public function app_userinfo() {
        global $_FANWE;

        $_FANWE['user']['avatar'] = avatar($_FANWE['user']['avatar'], 'b');
        $_FANWE['user']['needOldPassword'] = $_FANWE['user']['password'] != md5('xxxxxx');
        $_FANWE['user']['realname_wait'] = 0;
        $realname = FDB::fetchFirst('SELECT * FROM '.FDB::table("wogu_realname_shop").' WHERE uid='.$_FANWE['uid']);
        if(!empty($realname) && $realname['flag'] != 2) {
            $_FANWE['user']['realname_wait'] = 1;
        }

        exit(json_encode($_FANWE['user']));
    }

    public function mycoupon() {
        global $_FANWE;

        $sql = 'SELECT * FROM '.FDB::table('wogu_coupon').' WHERE to_uid = '.$_FANWE['uid'];
        $data = FDB::fetchAll($sql);
        if(!empty($data)) {
            $uids = array();
            foreach ($data as $v) {
                $uids[] = $v['from_uid'];
            }
            $sql = 'SELECT * FROM '.FDB::table('user').' WHERE uid IN('.implode(',', $uids).')';
            $res = FDB::query($sql);
            while($v = FDB::fetch($res)) {
                $users[$v['uid']] = $v;
            }
        }

        if(isset($_GET['ajax'])) {
            foreach ($data as $k => &$v) {
                $v['avatar'] = avatar($users[$v['from_uid']]['avatar'], 'm');
            }

            exit(json_encode(array(
                'list' => $data
            )));
        } else {
            include template('page/cp/mycoupon');
            display();
        }
    }

    public function yu() {
        global $_FANWE;

        if($_POST['doalipay'] || $_POST['dounionpay']) {
            $total_fee = $_POST['rmb'];
            $orderid = date('Ymdhis');
            $ordername = '火锅阁余额充值';
            $orderid_anli = intval($_GET['orderid']);
            $artid = intval($_GET['artid']);
            $paytype = isset($_POST['doalipay']) ? 0 : 1;
            FDB::insert('wogu_order_yu', array(
                'orderid' => $orderid,
                'paytype' => $paytype,
                'ordername' => $ordername,
                'orderid_anli' => $orderid_anli,
                'artid' => $artid,
                'userid' => $_FANWE['uid'],
                'total_fee' => $total_fee,
                'dateline' => time()
            ));

            if($paytype == 0) {
                require_once(FANWE_ROOT . 'payment/alipay.php');
                $aliapy_config = include(FANWE_ROOT . 'payment/alipay_config_new.php');

                //构造要请求的参数数组
                $parameter = array(
                    'service'            => 'create_direct_pay_by_user',
                    'payment_type'        => '1',
                    'partner'            => $aliapy_config['partner'],
                    '_input_charset'    => $aliapy_config['input_charset'],
                    'seller_email'        => $aliapy_config['seller_email'],
                    'return_url'        => $aliapy_config['return_url'],
                    'notify_url'        => $aliapy_config['notify_url'],
                    'out_trade_no'        => $orderid,
                    'subject'            => $ordername,
                    'body'                => $ordername,
                    'total_fee'            => $total_fee
                );

                //构造即时到帐接口
                $alipayService = new AlipayService($aliapy_config);
                $html_text = $alipayService->create_direct_pay_by_user($parameter);
                include template('page/article/article_dopayment');
                display();
            } else {
                include_once FANWE_ROOT . 'payment/unionpay_new/utf8/func/common.php';

                // 初始化日志
                $GLOBALS['log'] = new PhpLog ( SDK_LOG_FILE_PATH, "PRC", SDK_LOG_LEVEL );
                // 初始化日志
                $params = array(
                    'version' => '5.0.0',               //版本号
                    'encoding' => 'utf-8',              //编码方式
                    'certId' => getSignCertId (),           //证书ID
                    'txnType' => '01',              //交易类型
                    'txnSubType' => '01',               //交易子类
                    'bizType' => '000201',              //业务类型
                    'frontUrl' =>  SDK_FRONT_NOTIFY_URL,        //前台通知地址
                    'backUrl' => SDK_BACK_NOTIFY_URL,       //后台通知地址
                    'signMethod' => '01',       //签名方法
                    'channelType' => '08',      //渠道类型，07-PC，08-手机
                    'accessType' => '0',        //接入类型
                    'merId' => '898420148160352',               //商户代码，请改自己的测试商户号
                    'orderId' => $orderid,  //商户订单号
                    'txnTime' => date('YmdHis'),    //订单发送时间
                    'txnAmt' => $total_fee*100,       //交易金额，单位分
                    'currencyCode' => '156',    //交易币种
                    'defaultPayType' => '0001', //默认支付方式
                    //'orderDesc' => '订单描述',  //订单描述，网关支付和wap支付暂时不起作用
                    'reqReserved' =>' 透传信息', //请求方保留域，透传字段，查询、通知、对账文件中均会原样出现
                );
                // 签名
                sign ( $params );

                $front_uri = SDK_FRONT_TRANS_URL;
                $html_form = create_html ( $params, $front_uri );
                echo $html_form;
            }
        }

        include template('page/cp/yu');
        display();
    }
}
